package com.tpyule.tpclass.service.impl;

import com.tpyule.tpclass.dao.MenuDao;
import com.tpyule.tpclass.entity.bo.MenuDetailBo;
import com.tpyule.tpclass.entity.pojo.Menu;
import com.tpyule.tpclass.entity.pojo.MenuPath;
import com.tpyule.tpclass.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zzz
 * @version 1.0
 * @date 2020/5/5 9:56
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuDao menuDao;
    @Transactional
    @Override
    public int insertMenu(Menu menu, int[] paths) {
        menuDao.insertMenu(menu);
        if (menu.getId()!=0){
            for (int i = 0; i < paths.length; i++) {
                MenuPath mp = new MenuPath();
                mp.setMenuId(menu.getId());
                mp.setPathId(paths[i]);
                menuDao.insertMenuPath(mp);
            }
            return menu.getId();
        } else {
            return 0;
        }
    }

    @Override
    public List<MenuDetailBo> getListMenu(int roleId) {
        List<Menu> menus = menuDao.getListMenu(roleId);
        List<MenuDetailBo> bos = new ArrayList<>();
        for (int i=0;i<menus.size();i++){
            MenuDetailBo bo = new MenuDetailBo();
            bo.setId(menus.get(i).getId());
            bo.setRoleId(menus.get(i).getRoleId());
            bo.setType(menus.get(i).getType());
            List<MenuPath> paths = menuDao.getListMenuPathByMenuId(bo.getId());
            int[] pathIds = new int[paths.size()];
            for (int j = 0; j < paths.size(); j++) {
                pathIds[j]=paths.get(j).getPathId();
            }
            bo.setPathIds(pathIds);
            bos.add(bo);
        }
        return bos;
    }


    @Override
    public List<MenuPath> getListMenuPathByMenuId(int menuId) {
        return menuDao.getListMenuPathByMenuId(menuId);
    }

    @Transactional
    @Override
    public void updateMenuPath(Menu menu, int[] paths) {
        menuDao.deleteAllMenuPathByMenuId(menu.getId());
        for (int i = 0; i < paths.length; i++) {
            MenuPath mp = new MenuPath();
            mp.setMenuId(menu.getId());
            mp.setPathId(paths[i]);
            menuDao.insertMenuPath(mp);
        }
    }
}
